#-*- coding: utf-8 -*-

from usagi.paths import *
import subprocess
import gzip, codecs
import re

class Tango:
    def __init__(self,learned):
        self.kanjis = "".join(learned)

    def new_tango(self,kanji):
        cmd = 'zgrep "%s" %s'%(kanji, TANGO_PATH)
        p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, close_fds=True)
        notl = lambda i: not ((i==kanji) or i in self.kanjis or i<=u"\u30ff" or i >= u"\uff00")
        # u"\u30ff" is the first kanji and from u"\uff00" begin ascii chars
        new_words=[]
        inuni = codecs.getreader('utf-8')(p.stdout)
        for l in inuni:            
            word = l.split()[0]
            if kanji in word:
                if len(filter(notl, word))==0:
                    if word not in new_words:
                        new_words.append(word)
        self.kanjis+=kanji
        return new_words

#    def new_tango(self,kanji):
#        f = codecs.getreader('utf-8')(gzip.open(TANGO_PATH,'r'))
#        notl = lambda i: not ((i==kanji) or i in self.kanjis or i<=u"\u30ff" or i >= u"\uff00")
#        # u"\u30ff" is the first kanji and from u"\uff00" begin ascii chars
#        new_words=[]
#        for l in f:            
#            word = l.split()[0]
#            if kanji in word:
#                if len(filter(notl, word))==0:
#                    if word not in new_words:
#                        new_words.append(word)
#        self.kanjis+=kanji
#        f.close()
#        return new_words

class Word:
    def __init__(self,word):
        self.kanji = word
        self.interpretations = self._parse_lines(self._get_lines())

    def _parse_lines(self,lines):
        #format = re.compile(u'\w+\s+\[(\w+)\]\s*/\s*\(([^\(\) ]+)\)\s*([^/]+)((/[^/]+)*)/$', re.UNICODE)
        format = re.compile(u'\w+\s+\[(\w+)\]\s*/\s*((\([a-zA-Z][^\(\) ]*\)\s*)*)\s*([^/]+)((/[^/]+)*)/$', re.UNICODE)
        # Won't explain this
        interp = []
        for l in lines:
            g = re.match(format,l.strip()).groups() #It MUST match
            interp.append((g[0],g[1].strip("() ").split(") ("),(g[3]+g[4]).split("/")))
        return interp

#    def _get_lines(self):
#        f = gzip.open(TANGO_PATH,'r')        
#        dec = (self.kanji).encode('utf-8')+' '
#        l = f.readline()
#        lines = []
#        while(l):
#            if l.startswith(dec):
#                lines.append(unicode(l.split('\n')[0],'utf-8'))
#            l= f.readline()
#        f.close()
#        return lines

    def get_corpus(self):
        cmd = 'zgrep %s %s'%(self.kanji, TANAKA_PATH)
        p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, close_fds=True)
        return "\n".join([unicode(i.split('#')[0][3:].replace('\t','\n-'),'utf-8') for i in p.stdout.read().split('\n') if i.startswith('A: ')])

    def _get_lines(self):
        cmd = 'zgrep "^%s " %s'%(self.kanji, TANGO_PATH)
        p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, close_fds=True)
        return [unicode(i,'utf-8') for i in p.stdout.read().split('\n') if i]


